package com.aiatomic.couting;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.aiatomic.couting.models.TemplateEntity;
import com.aiatomic.couting.util.AppUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.GalleryPagerAdapter;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;
import androidx.drawerlayout.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private String savePath;
	private long exitTime = 0;
	private final int CAMBER = 2;// open camer
	private final int GALLERY = 1;// local images
	private final int WRITE_EXTERNAL_STORAGE = 100;
	private final int CAMERA = 101;
	public TemplateEntity currentTpl;
	DrawerLayout dl;
	View lv;
	private LinearLayout mViewPagerContainer;
	private ViewPager mGalleryViewPager;
	private int pos_last = 0;
	public static final String INTENT_AC_REFRESH_TEMPLATE = "refresh_templates";
	public static final Timer timer = new java.util.Timer(true);

	private boolean isGranted(String permission) {
		int checkSelfPermission = ActivityCompat.checkSelfPermission(this, permission);
		return checkSelfPermission == PackageManager.PERMISSION_GRANTED;
	}

	private void requestPermission(String permission, int requestCode) {
		if (!isGranted(permission)) {
			ActivityCompat.requestPermissions(this, new String[] { permission }, requestCode);
		} else {
			// 直接执行相应操作了
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		if (requestCode == CAMERA) {
			if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				openCamera();
//				requestCode == WRITE_EXTERNAL_STORAGE
			} else {
				finish();
				Toast.makeText(MainActivity.this, "您没有授权该权限，请在设置中打开授权", Toast.LENGTH_SHORT).show();
			}
			return;
		}
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			AppUtils.refresh_currency(MainActivity.this);

		}

	};

	@Override
	protected void onNewIntent(Intent intent) {
		if (INTENT_AC_REFRESH_TEMPLATE.equals(intent.getAction())) {
			initPageView();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		/*requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE);
		requestPermission(Manifest.permission.CAMERA, CAMERA);*/

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				Message msg = new Message();
				handler.dispatchMessage(msg);
			}
		};
		timer.schedule(task, 0, 15000);
		this.findViewById(R.id.topBar).setVisibility(android.view.View.INVISIBLE);
		this.findViewById(R.id.drawer_layout);
		lv = (View) findViewById(R.id.right_drawer);
		dl = (DrawerLayout) findViewById(R.id.drawer_layout);
		mViewPagerContainer = (LinearLayout) findViewById(R.id.pager_container);
		mGalleryViewPager = (ViewPager) this.findViewById(R.id.pager_viewer);
		mGalleryViewPager.setOffscreenPageLimit(5);
		mGalleryViewPager.setPageMargin(10);
		mGalleryViewPager.addOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				View childLast = mGalleryViewPager.getChildAt(pos_last);
				childLast.setBackgroundColor(getResources().getColor(R.color.material_grey_300));
				pos_last = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int state) {
				// 若viewpager滑动未停止，直接返回
				if (state != ViewPager.SCROLL_STATE_IDLE)
					return;
				// 若当前为第一张，设置页面为倒数第二张
				if (pos_last == 0) {
					mGalleryViewPager.setCurrentItem(mGalleryViewPager.getAdapter().getCount() - 2, false);
				} else if (pos_last == mGalleryViewPager.getAdapter().getCount() - 1) {
					// 若当前为倒数第一张，设置页面为第二张
					mGalleryViewPager.setCurrentItem(1, false);
				}
			}
		});
		initUI();
		initPageView();
		bindDrawerEvent();
	}

	private void initPageView() {
		List<TemplateEntity> localTpls = new ArrayList<TemplateEntity>();
		SystemUtil.getAllLocalStoreTemplates(this, localTpls);
		if (localTpls.size() == 0) {
			currentTpl = null;
			((TextView) (this).findViewById(R.id.current_selected_template)).setText("");
		}
		GalleryPagerAdapter adapter = new GalleryPagerAdapter(this, 10);
		adapter.setTemplates(localTpls);
		mGalleryViewPager.setAdapter(adapter);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				mGalleryViewPager.setCurrentItem(mGalleryViewPager.getAdapter().getCount() > 1 ? 1 : 0);
			}
		}, 100);
	}

	private void initUI() {
		TextView txtOpenGallery = (TextView) findViewById(R.id.txtOpenGallery);
		txtOpenGallery.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (currentTpl == null) {
					Toast toast = Toast.makeText(MainActivity.this, R.string.template_select, Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					return;
				}
				Intent intent = new Intent(Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(intent, GALLERY);
			}
		});
		TextView txtTakePicture = (TextView) findViewById(R.id.txtTakePicture);
		txtTakePicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean granted = isGranted(Manifest.permission.CAMERA);
				if(granted){

				openCamera();
				}else{
					requestPermission(Manifest.permission.CAMERA,CAMERA);
				}
			}
		});
		View accoutBottom = findViewById(R.id.accountBottomId);
		accoutBottom.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!AppUtils.isLogin(MainActivity.this)) {
					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
					MainActivity.this.startActivity(intent);
				} else {
					Intent intent = new Intent(MainActivity.this, AccountInfoActivity.class);
					intent.setAction(AccountInfoActivity.ACTION_MAIN);
					MainActivity.this.startActivity(intent);
				}
			}
		});

		View settingBottom = findViewById(R.id.settingBottomId);
		settingBottom.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, SettingActivity.class);
				MainActivity.this.startActivity(intent);
			}
		});

		View templatesBottom = findViewById(R.id.templatesBottomId);
		templatesBottom.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, TemplatesActivity.class);
				intent.setAction(TemplatesActivity.ACTION_FROM_MAIN);

				MainActivity.this.startActivity(intent);
			}
		});
		View moreBottom = findViewById(R.id.moreBottomId);
		moreBottom.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dl.openDrawer(lv);
			}
		});
		findViewById(R.id.next_arrow).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int itemId = mGalleryViewPager.getCurrentItem() + 1 >= mGalleryViewPager.getAdapter().getCount() ? 0
						: mGalleryViewPager.getCurrentItem() + 1;
				mGalleryViewPager.setCurrentItem(itemId, true);
			}
		});
		findViewById(R.id.prev_arrow).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int itemId = mGalleryViewPager.getCurrentItem() - 1 < 0 ? mGalleryViewPager.getAdapter().getCount() - 1
						: mGalleryViewPager.getCurrentItem() - 1;
				mGalleryViewPager.setCurrentItem(itemId, true);
			}
		});
	}

	private void openCamera(){
		if (currentTpl == null) {
			Toast toast = Toast.makeText(MainActivity.this, R.string.template_select, Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return;
		}
		Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

		savePath = MainActivity.this.getExternalCacheDir().getAbsolutePath() + "/capture_tmp.jpg";
		File capture = new File(savePath);
		if (capture.exists()) {
			capture.delete();
		}
		if (Build.VERSION.SDK_INT >= 24) {
			intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(MainActivity.this,
					"com.aiatomic.couting.fileprovider", capture));
		} else {
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(capture));
		}
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		startActivityForResult(intent, CAMBER);
	}

	private void bindDrawerEvent() {
		findViewById(R.id.drawer_close_layout).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dl.closeDrawer(lv);
			}
		});

		// quick_menu
		lv.findViewById(R.id.drawer_account).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!AppUtils.isLogin(MainActivity.this)) {
					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
					MainActivity.this.startActivity(intent);
				} else {
					Intent intent = new Intent(MainActivity.this, AccountInfoActivity.class);
					intent.setAction(AccountInfoActivity.ACTION_MAIN);
					MainActivity.this.startActivity(intent);
				}

			}
		});
		this.findViewById(R.id.drawer_about).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, AboutMeActivity.class);
				MainActivity.this.startActivity(intent);
			}
		});

		this.findViewById(R.id.drawer_buy).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				if (!AppUtils.isLogin(MainActivity.this)) {
//					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//					MainActivity.this.startActivity(intent);
//				} else {
//					Intent intent = new Intent(MainActivity.this, AccountInfoActivity.class);
//					intent.setAction(AccountInfoActivity.ACTION_SHOP);
//					MainActivity.this.startActivity(intent);
//				}
			}
		});
		this.findViewById(R.id.drawer_feedback).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!AppUtils.isLogin(MainActivity.this)) {
					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
					MainActivity.this.startActivity(intent);
				} else {
//					Intent intent = new Intent(MainActivity.this, AccountInfoActivity.class);
//					intent.setAction(AccountInfoActivity.ACTION_FEEDBACK);
//					MainActivity.this.startActivity(intent);
				}
			}
		});
		this.findViewById(R.id.drawer_setting).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, SettingActivity.class);
				MainActivity.this.startActivity(intent);
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast toast = Toast.makeText(getApplicationContext(), R.string.exit_app, Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
				toast.show();
				exitTime = System.currentTimeMillis();
			} else {
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				finish();
				// android.os.Process.killProcess(Process.myPid());
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CAMBER:
			if (resultCode == RESULT_OK) {
				if (savePath != null) {
					Intent scanIntent = new Intent(this, ScanActivity.class);
					scanIntent.setData(Uri.fromFile(new File(savePath)));
					scanIntent.putExtra("template", currentTpl);
					startActivity(scanIntent);
					savePath = null;
				}
			}
			break;
		case GALLERY: {
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				if (uri != null) {
					Intent scanIntent = new Intent(this, ScanActivity.class);
					scanIntent.setData(data.getData());
					scanIntent.putExtra("template", currentTpl);
					startActivity(scanIntent);
					/*
					 * InputStream input; try { input =
					 * this.getContentResolver().openInputStream(uri);
					 * BitmapFactory.Options onlyBoundsOptions = new
					 * BitmapFactory.Options(); Bitmap src =
					 * BitmapFactory.decodeStream(input, null,
					 * onlyBoundsOptions); input.close();
					 * 
					 * } catch (IOException e) { e.printStackTrace(); }
					 */
				}
			}
			break;
		}
		}

	}

}
